﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace android代码生成
{
    public partial class Form1 : Form
    {

        XmlDocument dom = new XmlDocument();
        OpenFileDialog of = new OpenFileDialog();
        List<String> valList = new List<string>();
        List<String> valType = new List<string>();
        public Form1()
        {

            InitializeComponent();
            of.InitialDirectory = System.Windows.Forms.Application.StartupPath;
        }

        void Clear()
        {
            valType.Clear();
            valList.Clear();
        }

        bool needClassHead()
        {
            return(textBoxLV.Text.Length > 0 || checkBoxSubView.Checked || checkBoxDialog.Checked);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            of.Title = "请选文件:";
            of.Filter = "xml文件(*.xml)|*.xml|所有文件|*.*";

            of.RestoreDirectory = true;

            if (of.ShowDialog() == DialogResult.OK)
            {

                string fileName =
                    of.FileName.Substring(of.FileName.LastIndexOf('\\') + 1).Replace(".xml", "");

                var className = new StringBuilder(fileName);
                className[0] = Char.ToUpper(className[0]);

                of.InitialDirectory = of.FileName;
                Clear();
                textBoxCode.Text = parserXml(of.FileName);

                StringBuilder sb = new StringBuilder(128);
                StringBuilder sb2 = new StringBuilder(128);

                String findViewPre = "";

                if (needClassHead())
                {
                    sb.Append(@"

import com.df.global.*;
import android.content.Context;
import android.content.Intent;
import android.widget.*;
import android.view.View;
import " + packName + @".R;
import butterknife.Bind;
import butterknife.ButterKnife;

public class "+className+@" {
");
                }

                for (int i = 0; i < valList.Count; i++)
                {
                    sb.Append(@"
    @Bind(R.id." + valList[i] + @")
    " + valType[i] + " " + valList[i] + @" = null;
");

                    if (valType[i] == "android.support.v4.view.ViewPager")
                    {
                        sb.Append("\r\n\t@Bind(R.id." + valList[i] + ")");
                        sb.Append("\r\n\tViewPageWrap pageWrap_" + valList[i] + " = null;\r\n");
                    }
                }

                if (checkBoxSubView.Checked || textBoxLV.Text.Length > 0)
                {
                    sb.Append(@"


    public " + className + @"(Context cont,View vi){
        if(vi == null)
            mView" + className + @" = Sys.createView(cont,R.layout." + fileName + @");
        else
            mView" + className + @" = vi;

	    mCont = cont;
        ButterKnife.bind(this, getView());
        initView(getView());
    }

    View mView" + className + @" = null;
    Context mCont = null;

    public View getView(){
    	return mView" + className + @";
    }

    public Context getContext(){
    	return mCont;
    }

    public View setTag(){
        getView().setTag(this);
        return getView();
    }


");
                    findViewPre = "vi.";
                }
                else if (checkBoxDialog.Checked)
                {
                     sb.Append(@"

    public android.app.Dialog dialog;
    Context mCont = null;

    public " + className + @"(final android.content.Context context){
        mCont = context;
        dialog = new android.app.Dialog(context);
        
        dialog.setContentView(R.layout." + fileName + @");
        ButterKnife.bind(this, dialog);
        initView(dialog);
    }


    public void show() {
        try {
            dialog.show();
        } catch (Exception e) {}
    }

    public void close() {
        try {
            dialog.dismiss();
        } catch (Exception e) {}
    }

");

                    findViewPre = "vi.";
                }


                if (textBoxLV.Text.Length > 0)
                {
                    sb.Append(@"
    // TODO *******展示每个item内容********
    public void showItem(final " + textBoxLV.Text + @" dat, final int index) {
        
      
    }
");
                }





               if (checkBoxSubView.Checked || textBoxLV.Text.Length > 0)
                {
                    sb.Append("\r\n\tvoid initView(android.view.View vi){\r\n");
                }
                else if (checkBoxDialog.Checked)
                {
                    sb.Append("\r\n\tvoid initView(android.app.Dialog vi){\r\n");
                }
                else
                {

                    sb.Append("\r\n\t@Override\r\n\tprotected void initView(){\r\n");
                }


                for (int i = 0; i < valList.Count; i++)
                {
                    if (textBoxLV.Text.Length > 0)
                    {
                    }
                    else
                    {

                        if (valType[i] == "RadioGroup")
                        {
                            sb.Append("\t" + valList[i] + ".setOnCheckedChangeListener(on_" + valList[i] + "_CheckedChange);\r\n");
                            sb2.Append("\r\n\r\n// TODO ********在此添加代码：RadioGroup事件*********\r\n");
                            sb2.Append("Sys.OnRadioCheckedChanged on_" + valList[i] + "_CheckedChange = new Sys.OnRadioCheckedChanged() {\r\n"
                            + "\t\t@Override\r\n\t\tpublic void run(RadioGroup arg0, int radioId) {\r\n\t\t\t\r\n\t\t}\r\n" +
                            "};\r\n");
                        }


                        if (valType[i].Contains("Button") || (valType[i] == "LinearLayout" && checkBoxLinear.Checked)
                            || (valType[i] == "TextView" && checkBoxTextView.Checked)
                            )
                        {
                            sb.Append("\t\tSys.setOnClick(" + valList[i] + ",v -> on_" + valList[i] + "_click(v));\r\n");

                            sb2.Append("\r\n\r\n\t// TODO ********在此添加代码：click事件*********\r\n");
                            sb2.Append("\tvoid on_" + valList[i] + "_click(android.view.View vi) {\r\n"
                            + "\t\t\t\r\n" +
                            "\t};\r\n");
                        }

                        if (valType[i] == "android.support.v4.view.ViewPager")
                        {

                            sb.Append("\tpageWrap_" + valList[i] + ".setOnPageSelected(on_" + valList[i] + "_selected);\r\n");

                            sb2.Append("\r\n\r\n// TODO ********在此添加代码：pageView切换事件*********\r\n");
                            sb2.Append("ViewPageWrap.OnPageSelected on_" + valList[i] + "_selected = new ViewPageWrap.OnPageSelected() {\r\n"
                            + "\t\t@Override\r\n\t\tpublic void run(int index) {\r\n\t\t\t\r\n\t\t}\r\n" +
                            "};\r\n");
                        }
                        else if (valType[i].Contains("ViewPageEx"))
                        {
                            sb.Append("\t" + valList[i] + ".setOnPageSelected(on_" + valList[i] + "_selected);\r\n");

                            sb2.Append("\r\n\r\n// TODO ********在此添加代码：pageView切换事件*********\r\n");
                            sb2.Append("ViewPageEx.OnPageSelected on_" + valList[i] + "_selected = new ViewPageEx.OnPageSelected() {\r\n"
                            + "\t\t@Override\r\n\t\tpublic void run(int index) {\r\n\t\t\t\r\n\t\t}\r\n" +
                            "};\r\n");
                        }
                    }

                }

                sb.Append("\r\n\t\t// TODO ********在此初始化*********\r\n\t\r\n\t\r\n\t}\r\n");


                if (textBoxLV.Text.Length > 0)
                {
                    sb.Append(@"
    public static ListViewEx<" + textBoxLV.Text + @"> newListViewEx(Context act,ListView lv){
          ListViewEx<" + textBoxLV.Text + @"> lve = new ListViewEx<" + textBoxLV.Text + @">(act,lv,
            (lvEx, vi, index) -> {
                if (vi == null)
                    vi = new " + className + @"(act,vi).setTag();

                try {
                    " + className + @" m = (" + className + @") vi.getTag();
                    " + textBoxLV.Text + @" dat = lvEx.get(index);
                    m.showItem(dat, index);
                } catch (Throwable e) {
                    Sys.logErr(e);
                }
                return vi;
             });

 
        lve.onItemClick = (index, vi) -> {
            " + className + @" m = (" + className + @") vi.getTag();
            " + textBoxLV.Text + @" dat = lve.get(index);
            // TODO ********在此添加代码：click事件*********
            
            
        };

        lve.onItemLongClick =(index, vi) -> {
            " + className + @" m = (" + className + @") vi.getTag();
            " + textBoxLV.Text + @" dat = lve.get(index);
            // TODO ********在此添加代码：long click事件*********
            
            
            
            return false;
        };

        return lve;
    }
");
                }


                if (needClassHead())
                {
                    sb2.Append(@"

///////class end///////
}
");
                }

                textBoxCode.Text += sb.ToString();
                textBoxCode.Text += sb2.ToString();
            }


        }
        void parserNode(XmlNode node)
        {
            StringBuilder sb = new StringBuilder(128);

            for (XmlNode n = node; n != null; n = n.NextSibling)
            {
                try
                {
                    var id = n.Attributes["android:id"];

                    if (id != null)
                    {
                        String val = id.Value.Replace("@+id/", "").Replace("@android:id/", "");
                        String type = n.Name;
                        if (type == "include")
                            type = "android.view.View";

                        if (type == "RadioButton")
                            continue;

                        valList.Add(val);
                        valType.Add(type);

                        //sb.Append(type + " " + val + " = null;\r\n");

                    }
                }
                catch (Exception)
                {


                }

                var child = n.FirstChild;
                if (child != null)
                {
                    parserNode(child);
                }


            }


        }



        string parserXml(String file)
        {
            StringBuilder sb = new StringBuilder(128);

            dom.Load(file);

            parserNode(dom.DocumentElement);




            return sb.ToString();
        }

        /// <summary>
        ///  //剪贴板
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool SetClipboard(string str)
        {
            try
            {
                Clipboard.SetDataObject(str, true);
            }
            catch (System.Exception ex)
            {

                return false;
            }
            return true;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            SetClipboard(textBoxCode.Text);
        }

        String packName = "";

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                String res = File.ReadAllText("AndroidManifest.xml");
                int start = res.IndexOf("package");
                for (int i = start; i < res.Length; i++)
                {
                    if (res[i] == '"')
                    {
                        start = i+1;
                        break;
                    }
                }

                for (int i = start; i < res.Length; i++)
                {
                    if (res[i] == '"')
                    {
                        start = i;
                        break;
                    }

                    packName += res[i];
                }

            }
            catch (Exception)
            {

            }
            labelPack.Text = packName;
        }

        private void 生成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            String head="<resources>\r\n";
            String foot="\r\n</resources>";

            for (int scr = 80; scr <= 1280; scr+=40)
            {
                String fileW="values-w" + scr + "dp";
                String fileH="values-h" + scr + "dp";
                Directory.CreateDirectory(fileW);
                Directory.CreateDirectory(fileH);
                String w = "", h = "";
                for (int i = 2; i < 100; i += 2)
                {
                    float val=(float)scr/100*i;
                    w += "\r\n\t<dimen name=\"percent_w" + i + "\">" + (int)val + "dip</dimen>\r\n";
                    h += "\r\n\t<dimen name=\"percent_h" + i + "\">" + (int)val + "dip</dimen>\r\n";
                }

                File.WriteAllText(fileW + "/dimens.xml", head + w + foot);
                File.WriteAllText(fileH + "/dimens.xml", head + h + foot);
              
            }
            MessageBox.Show("ok");
        }


    }
}
